Ext.ns("org.cancerregulome.redi");

org.cancerregulome.redi.PathedMenu = Ext.extend(Ext.menu.Menu, {
    menusByPath: {},
    menuItems: [],

    constructor: function(config) {
        Ext.apply(this, config);
        org.cancerregulome.redi.PathedMenu.superclass.constructor.call(this);
    },

    buildMenus: function(sorter) {
        this.menuItems.sort(sorter);
        Ext.each(this.menuItems, function(menuItem) {
            if (menuItem && menuItem.path) {
                var parts = menuItem.path.split("/");
                var lastMenu = this;
                var currentPath = "";

                for (var i = 1; i < parts.length; i++) {
                    var part = parts[i];
                    currentPath += "/" + part;
                    var existingMenu = this.menusByPath[currentPath];
                    if (!existingMenu) {
                        existingMenu = new Ext.menu.Menu({path:currentPath});
                        this.menusByPath[currentPath] = existingMenu;
                        lastMenu.add({text:part, menu: existingMenu});
                    }
                    lastMenu = existingMenu;
                }

                lastMenu.addMenuItem(menuItem);
            }
        }, this);
    }
});
